<template>
  <div class="private-box">
    <div
      class="left bdradius4"
      ref="privateboxleft"
    >
      <div class="left-title">
        <span class="left-title-left">用户</span>
        <el-button
          icon="el-icon-plus"
          size="mini"
          @click="addRole()"
        ></el-button>
        <!-- <img
          src="../../../assets/img/add.png"
          alt=""
          class="left-title-right"
        /> -->
      </div>
      <div class="block">
        <org-structure
          @search="onTreeSearch"
          ref="orgStructure"
          :deptList="deptList"
        ></org-structure>
      </div>
    </div>
    <div class="right">
      <div class="right-top bdradius4 mb12">
        <Icon
          type="ios-person"
          color="#1577FE"
          size="22"
          class="right-top-icon"
        />
        <span>{{ jiaosename }}</span>
      </div>
      <div
        class="right-bot bgFFF bdradius4 mb12"
        :style="{ height: Height + 'px' }"
      >
        <div
          class="right-bot-box"
          style="width: 100%"
        >
          <!-- <div class="right-bot-box-title">操作权限</div>
          <div class="right-bot-box-cont">
            <el-tree
              :data="threedata"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="trees"
              highlight-current
              :props="defaultProps"
              @check="caozcheck"
            >
            </el-tree>
          </div> -->
          <div class="right-bot-box-cont">
            <div
              v-for="(item, index) in threedata"
              :key="index"
              style="margin-bottom:20px;border-top: 1px solid #DDDDDD;border-right: 1px solid #DDDDDD;border-left: 1px solid #DDDDDD;"
            >
              <div style="background:#F4F9FF;border-bottom:1px solid #DDDDDD;padding:20px 0 20px 20px">
                <CheckboxGroup
                  v-model="checkboxValue"
                  @on-change="changeCheckbox($event, index, 1,item)"
                >
                  <div :key="item.id">
                    <Checkbox
                      :label="item.id"
                      style="font-weight: 600;"
                    >
                      <!-- :indeterminate="indeterminate1" -->
                      {{ item.menuName || "" }}
                    </Checkbox>
                  </div>
                </CheckboxGroup>
              </div>
              <div v-if="item.childrenList.length > 0">
                <div
                  style="border-bottom:1px solid #DDDDDD;padding:20px 0 20px 38px;display: flex;align-items: self-end;"
                  v-for="(itemC,indexC) in item.childrenList"
                  :key="indexC"
                >
                  <CheckboxGroup
                    v-model="checkboxValue"
                    @on-change="changeCheckbox($event, index,2,itemC,indexC)"
                    style="display: flex;align-items: flex-end;"
                  >
                    <Checkbox
                      :label="itemC.id"
                      style="width:130px;font-weight: 600;"
                    >
                      {{ itemC.menuName || "" }}
                    </Checkbox>
                    <div
                      v-if="itemC.childrenList.length > 0"
                      style="display:flex"
                    >
                      <div
                        v-for="(itemCC,indexCC) in itemC.childrenList"
                        :key="indexCC"
                      >
                        <CheckboxGroup
                          v-model="checkboxValue"
                          @on-change="changeCheckbox($event, index,3,itemCC,indexC)"
                        >
                          <Checkbox
                            :label="itemCC.id"
                            style="margin-right:20px"
                          >
                            {{ itemCC.menuName || "" }}
                          </Checkbox>
                        </CheckboxGroup>
                      </div>
                    </div>
                  </CheckboxGroup>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div
        class="private-box-right-bot bdradius4"
      >
        <div @click="baocun">保存</div>
      </div>
    </div>
    <!-- 添加角色 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addRoleDialog"
      :close-on-click-modal='false'
    >
      <el-form
        :model="addRoleForm"
        :rules="rules"
        ref="addRoleForm"
      >
        <el-form-item
          label="用户名"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input
            v-model="addRoleForm.name"
            autocomplete="off"
          ></el-input>
        </el-form-item>

      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="outRoleSubmit">取 消</el-button>
        <el-button
          type="primary"
          @click="addRoleSubmit('addRoleForm')"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import orgStructure from "./orgStructure";
import { addrole, getrole, getmenuList } from '@/api/data.js'
import { compileRoleMenu } from '@/api/data.js'

export default {
  components: {
    orgStructure,
  },
  data () {
    return {
      formLabelWidth: '120px',
      addRoleDialog: false,
      addRoleForm: {
        name: ''
      },
      rules: {
        name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 10, message: '长度为2到10个字符', trigger: 'blur' }
        ]
      },
      //   indeterminate1: true,
      indeterminate2: true,
      indeterminate3: true,
      checkboxValue: [],
      checkAllGroup: "",
      buttonRight: [],
      xuanzlist: [],
      jiaosename: "",
      roleId: "",
      Height: "",
      towdata: [],
      threedata: [],
      defaultProps: {
        children: "childrenList",
        label: "menuName",
      },
      deptList: []
    };
  },
  created () {
    // 角色列表获取
    this.getcharacter()
    // this.axios.post('/zwgrid/v1/add/roles', { roleName: '县级管理员' }).then(res => {
    //   console.log(res);
    // })
    this.APIS.addRole({ roleName: '县级管理员' }).then(res => {
      console.log(0);
      console.log(res);
    })
    let buttonMenu = this.buttonMenu(this.$route.name);
    this.buttonRight = buttonMenu.buttonRight;

    // 获取 DOM 元素
    this.$nextTick(() => {
      let $ele = this.$refs.privateboxleft;
      let height = window.getComputedStyle($ele).height;
      this.Height = height.replace("px", "") - 141;
    });
  },
  methods: {
    // 获取角色列表
    async getcharacter() {
      const res = await getrole({})
      console.log('角色列表', res);
      this.jiaosename = res[0].roleName
      const ress = await getmenuList({
        rolesId: res[0].id
      })
      this.checkboxValue = ress.xuanZhongList
      this.deptList = res
      console.log('deptList', this.deptList);
      this.MenuList()
    },
    // 获取菜单列表
    async MenuList() {
      console.log('a');
      console.log(this.deptList[0].id);
      const ress = await getmenuList({
        rolesId: this.deptList[0].id
      })
      console.log('菜单列表', ress);
      this.threedata = ress.childrenList
      // this.checkboxValue = ress.xuanZhongList
      // this.jiaosename = this.deptList[0].roleName
    },
    
    addRole () {
      this.addRoleDialog = true;
    },
    // 新增角色弹窗确定
    addRoleSubmit (addRoleForm) {
      console.log(addRoleForm);
      this.$refs[addRoleForm].validate(async valid => {
        if (valid) {
          // this.APIS.addRole(this.addRoleForm).then(res => {
          //   console.log(res);
          //   this.addRoleDialog = false;
          //   this.$refs.orgStructure.departmentList()
          // })
          const res = await addrole({
            roleName: this.addRoleForm.name
          })
          this.getcharacter()
          this.addRoleDialog = false
          this.addRoleForm.name = ''
        }
      })
    },
    // 新增角色弹窗取消
    outRoleSubmit() {
      this.addRoleDialog = false
      this.addRoleForm.name = ''
    },
    changeCheckbox (data, index, parent, item, indexCC) {
      console.log('勾选了');
      console.log(data, 'data');
      console.log(index, 'index');
      console.log(parent, 'parent');
      console.log(item, 'item');
      console.log(indexCC, 'indexCC');
      // data 选中的总数组
      console.log(this.threedata);
      let dataItem = this.threedata[index];
      console.log(dataItem);
      // 解析
      //   权限暂时只有三级，所以只渲染三套，因为是手写所以手动渲染，parent==1代表一级菜单parent==2代表二级菜单parent==3代表三级菜单，不同的菜单需要有不同的联动操作逻辑
      // 1.
      //   一级菜单选中时循环量级都判断data中是否已经选中如果没有选中那就push进去，一级菜单取消选中时二级菜单和三集菜单全部取消选中
      // 2.
      //   二级菜单需要联动上面的一级菜单和下面的三级菜单，二级菜单选中时一级菜单也选中，只要有二级菜单选中一级菜单就是选中状态并且三级菜单全部选中，
      // 二级菜单取消选中时需要判断是否是最后一个未选中的二级菜单如果是最后一个那么需要把一级菜单也取消选中（比如一级菜单下有两个二级菜单那么如果两个都为非选中的时候一级菜单也需要取消选中）
      // 并且三级菜单需要全部取消选中
      // 3.
      //   三级菜单需要联动二级菜单和一级菜单，三级菜单选中时该三级菜单的二级菜单和一级菜单都要选中，并且需要判断该三级菜单如果全部都是未选中状态那么该三级菜单的二级菜单也是未选中，
      // 三级菜单取消选中需要判断该三级菜单是否全部取消选中如果是那么该三级菜单的二级菜单也需要取消选中，还需要判断是否是全部的三级菜单取消选中，如果三级菜单全部取消选中那么该三级菜单的
      // 二级菜单和一级菜单也需要取消选中（比如一个一级菜单下有两个二级菜单，两个二级菜单下均有两个三级菜单，此时的结构是一个一级菜单两个二级菜单四个三级菜单，如果两个二级菜单下的所有三级菜单
      // 都取消选中那么在最后一个取消选中的时候需要把该三级菜单的二级菜单和一级菜单都取消选中，因为是只要有一个三级菜单选中那么这个三级菜单的二级菜单和一级菜单都要选中的）
      if (parent == 1) {
        // 一级菜单
        console.log(data.indexOf(item.id));
        let id = item.id
        for (let i = 0; i < dataItem.childrenList.length; i++) {
          if (data.includes(dataItem.childrenList[i].id)) {
            console.log('id为' + id + '的一级菜单没有全选');
            break;
          }
        }
        if (data.indexOf(item.id) == -1) {
          // console.log('取消勾选')
          for (let i = 0; i < dataItem.childrenList.length; i++) {
            for (let ii = 0; ii < data.length; ii++) {
              if (data[ii] == dataItem.childrenList[i].id) {
                data.splice(ii, 1);
                break;
              }
            }
            for (let n = 0; n < dataItem.childrenList[i].childrenList.length; n++) {
              for (let ni = 0; ni < data.length; ni++) {
                if (data[ni] == dataItem.childrenList[i].childrenList[n].id) {
                  data.splice(ni, 1);
                  break;
                }
              }
            }
          }
        } else {
          // console.log('勾选')
          for (let i = 0; i < dataItem.childrenList.length; i++) {
            if (data.indexOf(dataItem.childrenList[i].id) == -1) {
              data.push(dataItem.childrenList[i].id);
            }
            for (let n = 0; n < dataItem.childrenList[i].childrenList.length; n++) {
              if (data.indexOf(dataItem.childrenList[i].childrenList[n].id) == -1) {
                data.push(dataItem.childrenList[i].childrenList[n].id);
              }
            }
          }
        }
        console.log('1parent', data);
        this.checkboxValue = data
      } else if (parent == 2) {
        // 二级菜单
        if (data.indexOf(item.id) == -1) {
          // 取消勾选
          var arrtow = [];
          for (let i = 0; i < dataItem.childrenList.length; i++) {
            arrtow.push(dataItem.childrenList[i].id);
          }
          var arrheji = arrtow.filter(function (val) {
            return data.indexOf(val) > -1;
          });
          // 取消最后一个二级节点触发 二级节点全部取消 一级节点也取消
          if (arrheji.length == 0) {
            for (let i = 0; i < data.length; i++) {
              if (data[i] == dataItem.id) {
                data.splice(i, 1);
                break;
              }
            }
          }
          for (let l = 0; l < item.childrenList.length; l++) {
            for (let i = 0; i < data.length; i++) {
              if (data[i] == item.childrenList[l].id) {
                data.splice(i, 1);
                break;
              }
            }
          }
        } else {
          // 勾选
          if (data.indexOf(dataItem.id) == -1) {
            data.push(dataItem.id);
          }
          // 二级 选中时 三级全部选中
          item.childrenList.map((items) => {
            if (!data.includes(items.id)) {
              data.push(items.id);
            }
          });
        }
        console.log('2parent', data);

      } else if (parent == 3) {
        // 三级菜单
        if (data.indexOf(item.id) == -1) {
          // 取消勾选
          var arrtow = [];
          for (
            let i = 0;
            i < dataItem.childrenList[indexCC].childrenList.length;
            i++
          ) {
            arrtow.push(dataItem.childrenList[indexCC].childrenList[i].id);
          }
          var arrheji = arrtow.filter(function (val) {
            return data.indexOf(val) > -1;
          });
          // 取消最后一个二级节点触发 二级节点全部取消 一级节点也取消
          if (arrheji.length == 0) {
            for (let i = 0; i < data.length; i++) {
              if (data[i] == dataItem.childrenList[indexCC].id) {
                data.splice(i, 1);
                break;
              }
            }
          }
          // 三级菜单全部取消勾选时一级菜单也需要取消转钟
          var fuarrtow = [];
          for (let i = 0; i < dataItem.childrenList.length; i++) {
            fuarrtow.push(dataItem.childrenList[i].id);
          }
          var tsarrheji = fuarrtow.filter(function (val) {
            return data.indexOf(val) > -1;
          });
          if (tsarrheji.length == 0) {
            for (let i = 0; i < data.length; i++) {
              if (data[i] == dataItem.id) {
                data.splice(i, 1);
                break;
              }
            }
          }
        } else {
          // 勾选
          if (data.indexOf(dataItem.childrenList[indexCC].id) == -1) {
            data.push(dataItem.childrenList[indexCC].id);
          }
          if (data.indexOf(dataItem.id) == -1) {
            data.push(dataItem.id);
          }
        }
        console.log('3parent', data);

      }
      this.checkboxValue = data;
    },
    // 修改功能权限和操作权限方法
    async baocun () {
      // // 操作权限
      // //返回选中子节点的key
      // let childs = this.$refs.trees.getCheckedKeys();
      // //返回选中子节点的父节点的key
      // let parents = this.$refs.trees.getHalfCheckedKeys();
      // // 选中的节点和半选的节点的合集
      // let checkNodes = childs.concat(parents);
      // // 功能权和操作权限合集
      // var hejilist = checkNode.concat(checkNodes)
      // this.APIS.sysMenu({
      //   roleId: this.roleId,
      //   menuIdList: this.checkboxValue,
      // }).then((res) => {
      //   if (res.code == 20000) {
      //     this.$Message.success("修改成功");
      //   }
      // });
      const res = await compileRoleMenu({
        rolesId: this.roleId,
        menuIdList: this.checkboxValue
      })
      console.log('保存', res);
      this.getcharacter()
    },
    // 获取操作权限列表数据
    getcaozdata () {
      this.APIS.roleLevelThree({ roleId: this.roleId }).then((res) => {
        this.threedata = res.data.childrenList;
        this.checkboxValue = res.data.xuanZhongList;
        // res.data.xuanZhongList.forEach((id) => {
        //   this.$nextTick(() => {
        //     var node = this.$refs.trees.getNode(id);
        //     // isLeaf为tree组件自带属性，用于判断当前节点是否为子节点
        //     if (node.isLeaf) {
        //       // 只选中子节点，父节点自动为半选中状态
        //       this.$refs.trees.setChecked(node, true);
        //     }
        //   });
        // });
      });
    },
    // 操作权限树chang
    caozcheck (e, r) {
      this.xuanzlist = r.checkedKeys;
    },
    // 切换角色回调
    onTreeSearch (data, res) {
      this.roleId = data.id;
     
      // if (data.roleName != "默认角色") {
      //   // this.getcaozdata();
      // }
      // this.getcharacter()
      console.log(res.xuanZhongList);
      this.jiaosename = data.roleName;
      this.checkboxValue = res.xuanZhongList
    },
  },
};
</script>

<style scoped lang="less">
/deep/.ivu-checkbox {
  margin-right: 4px;
}
.private-box-right-bot {
  height: 64px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  div {
    cursor: pointer;
    color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 65px;
    height: 32px;
    background: #1577fe;
    border-radius: 2px;
  }
}
.private-box {
  width: 100%;
  height: 100%;
  display: flex;
  background: #f0f2f5;
  justify-content: space-between;
  .left {
    width: 340px;
    background: #fff;
    .left-title {
      margin: 14px 0;
      padding: 0 20px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .left-title-left {
      }
      .left-title-right {
        width: 15px;
        height: 15px;
        color: #1577fe;
      }
    }
  }
  .right {
    width: 71.5%;
    //background: #fff;
    display: flex;
    flex-direction: column;
    flex: 1;
    margin-left: 12px;
    .right-top {
      height: 53px;
      background: #fff;
      display: flex;
      align-items: center;
      .right-top-icon {
        margin: 0 13px 0 23px;
      }
    }
    .right-bot {
      width: 100%;
      padding: 12px;
      display: flex;
      .right-bot-box {
        display: flex;
        flex-direction: column;
        .right-bot-box-title {
          margin: 0 0 12px 0;
        }
        .right-bot-box-cont {
          height: 100%;
          overflow: auto;
        }
      }
    }
  }
}
</style>
